package com.moon.app;

import java.util.LinkedList;

import org.apache.commons.lang.time.StopWatch;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.moon.R;
import com.moon.adapter.TopicListAdapter;
import com.moon.common.AbstractActivity;
import com.moon.constants.MoonConstants;
import com.moon.model.Topic;
import com.moon.model.TopicListJsonResult;
import com.moon.utils.JacksonUtils;

/**
 * TOPIC列表
 * 
 * @author paul
 * @date 2014年5月17日
 */
public class TopicListActivity extends AbstractActivity{
    private static final String   TAG      = TopicListActivity.class.getSimpleName();

    //上拉加载下面的数据后,再下拉会重新加数的问题, 此时不需要直接加载数据,因为老数据已经在列表中
    //private SwipeRefreshLayout    topicSwipeLayout;

    /**
     * PullToRefreshListView
     */
    private PullToRefreshListView listView;

    /**
     * ListView适配器
     */
    private TopicListAdapter      adapter;

    private LinkedList<Topic>     topicList;

    Integer                       pageNo   = 1;                                      //目前来说,永远是1  可以不要
    Integer                       pageSize = 10;
    Long                          topTopicId;
    Long                          bottomTopicId;
    RequestQueue mQueue ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.topic_list);
        mQueue = Volley.newRequestQueue(getApplicationContext());
//        topicSwipeLayout = (SwipeRefreshLayout) this.findViewById(R.id.topic_swipe_list);
//        topicSwipeLayout.setOnRefreshListener(this);

//        // 顶部刷新的样式
//        topicSwipeLayout.setColorScheme(android.R.color.holo_green_light,
//                android.R.color.holo_blue_bright, android.R.color.holo_orange_light,
//                android.R.color.holo_red_light);

        //取列表
        //读内存数据
        listView = (PullToRefreshListView) this.findViewById(R.id.topic_list_view);
        listView.setMode(Mode.BOTH);//上下拉都可以
        listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 下拉的时候数据重置  --重新加载第一页数据
                //使用SwipeRefreshLayout.OnRefreshListener 来做了,没有在此处理,也可以使用这块
               // topicSwipeLayout.setRefreshing(false);
                listTopicString(true);
                
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                // 上拉的时候添加选项   -- 把数据加到已有的topicList

                listTopicString(false);

                //new FinishRefresh().execute();  

            }
        });
        topicList = new LinkedList<Topic>();//用于展现
        adapter = new TopicListAdapter(this, topicList);
        listView.setAdapter(adapter);
        listTopicString(true);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Topic topic = (Topic) parent.getItemAtPosition(position);
                Intent intent = new Intent(TopicListActivity.this, TopicViewActivity.class);
                intent.putExtra(MoonConstants.TOPIC_OBJECT_KEY,
                        topic);
                startActivity(intent);
            }
        });
//        listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
//            
//            @Override
//            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
//                menu.setHeaderTitle("ContextMenu");       
//                menu.add(0, 0, 0, "Delete this favorite!");   
//                
//            }
//        });
    }

//    @Override
//    public void onRefresh() {
////        topicSwipeLayout.setRefreshing(false);
////        listTopicString(true);
//    }

    private void listTopicString(final boolean isPullDown) {
        final StopWatch watch = new StopWatch();
        watch.start();
        try {
            //拼装url
            String requestUrl = "/mobile_topic/list_topic.do?pageNo=" + pageNo + "&categoryId="
                    + MoonConstants.APP_SQUARE_CATEGORY_ID + "&pageSize=" + pageSize;
            if (!isPullDown && bottomTopicId!= null) {//此时取bottomTopicId后面的20条
                requestUrl = requestUrl + "&bottomTopicId=" + bottomTopicId;
            }

            
            mQueue.add(new StringRequest(MoonConstants.MOON_DOMAIN + requestUrl,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            watch.stop();
                            Log.e(TAG, "topiclist  ------------------->"+watch.getTime());

                            TopicListJsonResult result = JacksonUtils.fromJSON(response,
                                    TopicListJsonResult.class);
                            if (result.isSuccess()) {
                                //插入数据List
                                addTopicList(isPullDown, result.getObject());

                                //更新ui
                                adapter.notifyDataSetChanged();

                                //完成刷新ui
                                listView.onRefreshComplete();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(getApplicationContext(), "获取更新失败", Toast.LENGTH_SHORT)
                                    .show();

                        }

                    }));
            //mQueue.start();
        } catch (Exception e) {
            Log.e(TAG, "listTopic error", e);
        }
    }

    private void addTopicList(boolean isPullDown, LinkedList<Topic> topics) {
        if (topics == null || topics.size() == 0) {
            return;
        }

        //下拉为重置数据
        //上拉为加载数据
        if (isPullDown) {
            topicList.clear();
        }
        for (Topic topic : topics) {
            topicList.addLast(topic);
        }

        //更新上下id   
        if (isPullDown) {
            //顶部ID
            topTopicId = topics.getFirst().getId();
            //底部ID
            bottomTopicId = topics.getLast().getId();
        } else {
            bottomTopicId = topics.getLast().getId();
            if (topTopicId == null) {
                topTopicId = topics.getFirst().getId();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem send = menu.add("send");
        send.setIcon(android.R.drawable.ic_input_add);
        send.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);//作为按钮显示
        send.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent intent = new Intent(TopicListActivity.this, TopicSendActivity.class);
                intent.putExtra(MoonConstants.TOPIC_CATEGORY_ID,
                        MoonConstants.APP_SQUARE_CATEGORY_ID);
                startActivity(intent);
                return true;
            }
        });
        //search.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    //以下是使用JsonObjectRequest   但返回JSONObject  无法正常转换成List<Topic>  ,所以还是使用StringRequest吧
    //    private void listTopic() {
    //        try {
    //            pageNo++;
    //            String requestUrl = "/mobile_topic/list_topic.do";
    //            final JSONObject jsonRequest = new JSONObject();
    //            jsonRequest.put(MoonConstants.TOPIC_CATEGORY_ID, MoonConstants.APP_SQUARE_CATEGORY_ID);
    //            jsonRequest.put(MoonConstants.TOPIC_LIST_PAGE_NO, pageNo);
    //            jsonRequest.put(MoonConstants.TOPIC_LIST_PAGE_SIZE, pageSize);
    //
    //            RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
    //            mQueue.add(new JsonObjectRequest(Method.POST, MoonConstants.MOON_DOMAIN + requestUrl,
    //                    jsonRequest, new Response.Listener<JSONObject>() {
    //                        @Override
    //                        public void onResponse(JSONObject response) {
    //                            try {
    //                                if (response.getBoolean("success")) {
    //                                    String data = response.getString("object");
    //                                    List<Topic> topicTemp = JacksonUtils.fromJSON(data, List.class);
    //                                    topicList.addAll(topicTemp);
    //                                    adapter.notifyDataSetChanged();
    //                                }
    //                            } catch (JSONException e) {
    //                                // TODO Auto-generated catch block
    //                                e.printStackTrace();
    //                            }
    //                            System.out.println(response);
    //                        }
    //                    }, new Response.ErrorListener() {
    //                        @Override
    //                        public void onErrorResponse(VolleyError error) {
    //                            Toast.makeText(getApplicationContext(), "获取列表失败", Toast.LENGTH_SHORT)
    //                                    .show();
    //                        }
    //                    }));
    //            mQueue.start();
    //        } catch (Exception e) {
    //            Log.e(TAG, "listTopic error", e);
    //        }
    //
    //    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 退出提示
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            startActivity(new Intent(this, MainActivity.class));
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
